package com.dhecp.project.business.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.utils.MessageUtils;
import com.dhecp.common.utils.RandomValueUtils;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.DataFiltering;
import com.dhecp.core.utils.PageUtils;
import com.dhecp.core.utils.ReflectUtils;
import com.dhecp.project.business.domain.ProductMG;
import com.dhecp.project.business.mapper.ProductMGMapper;
import com.dhecp.project.business.service.ProductMGService;
import com.dhecp.project.common.domain.ModuleNID;
import com.dhecp.project.common.domain.RecordCheck;
import com.dhecp.project.common.domain.UpdateDeleted;
import com.dhecp.project.common.domain.UpdateFlow;
import com.dhecp.project.common.service.impl.BaseModuleServiceImpl;
import com.dhecp.project.system.service.SysDictionaryForFieldService;

/**
 * 商品美图 服务层
 * @author DH-Xxj
 * @version 2022年7月28日
 */
@Service
public class ProductMGServiceImpl extends BaseModuleServiceImpl implements ProductMGService {

	@Autowired
	private ProductMGMapper businessMapper;
	
	@Autowired
	private SysDictionaryForFieldService dictionaryForFieldService;
	
	/**
	 * 查询前一单NID、BID
	 * @param nid 必要参数：当前 单据编码
	 * @return AjaxResult (data.nid 前一单NID， data.bid 前一单BID)
	 * @author DH-Xxj
	 * @throws Exception  
	 */
	@Override
	public AjaxResult queryLastNid(Map<String, Object> params) throws Exception {
		Map<String, Object> dataMap = new HashMap<String, Object>();
		if (params.get("nid") == null || params.get("nid") == ""){
			params.put("nid", "0");   
		}
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        ModuleNID moduleNID = businessMapper.selectLastNid(params);
        if (moduleNID == null){
        	dataMap.put("nid", "0");
        	dataMap.put("bid", "0");
        	return AjaxResult.warn(MessageUtils.message("module.warn.isfirstnid"), TypeUtils.mapToJson(dataMap).toString());
        }
    	dataMap.put("nid", moduleNID.getNid().toString());
    	dataMap.put("bid", moduleNID.getBid().toString());
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), TypeUtils.mapToJson(dataMap).toString());
	}
	
	/**
	 * 查询后一单NID、BID
	 * @param nid 必要参数：当前 单据编码
	 * @return AjaxResult (data.nid 后一单NID， data.bid 后一单BID)
	 * @author DH-Xxj
	 * @throws Exception  
	 */
	@Override
	public AjaxResult queryNextNid(Map<String, Object> params) throws Exception {
		Map<String, Object> dataMap = new HashMap<String, Object>();
		if (params.get("nid") == null || params.get("nid") == "" || "0".equals(params.get("nid").toString())){
        	dataMap.put("nid", "0");
        	dataMap.put("bid", "0");
			return AjaxResult.warn(MessageUtils.message("module.warn.isfinallynid"), TypeUtils.mapToJson(dataMap).toString());
		}
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        ModuleNID moduleNID = businessMapper.selectNextNid(params);
        if (moduleNID == null){
        	dataMap.put("nid", "0");
        	dataMap.put("bid", "0");
        	return AjaxResult.warn(MessageUtils.message("module.warn.isfinallynid"), TypeUtils.mapToJson(dataMap).toString());
        }
    	dataMap.put("nid", moduleNID.getNid().toString());
    	dataMap.put("bid", moduleNID.getBid().toString());
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), TypeUtils.mapToJson(dataMap).toString());
	}
	
	/**
	 * 查询指定单nid的首记录
	 * @param nid 必要参数：当前 单据编码
	 * @return ProductMG
	 * @throws Exception
	 * @author DH-Xxj
	 */
	@Override
	public ProductMG queryFirstRecord(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
		return businessMapper.selectFirstRecordByNid(params);
	}
	
	/**
	 * 查询指定单nid的整单录
	 * @param nid 必要参数：当前 单据编码
	 * @return List - ProductMG
	 * @throws Exception
	 * @author DH-Xxj
	 */
	@Override
	public List<ProductMG> queryListByNid(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        return businessMapper.selectByNid(params);
	}
	
	/**
	 * 查询
	 * @param params
	 * @return List - ProductMG
	 * @throws Exception
	 * @author DH-Xxj
	 */
	@Override
    public List<ProductMG> queryList(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));	//常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        PageUtils.startPageStronger();
        return businessMapper.select(params);
    }
	
	/**
	 * 分组（整单）查询
	 * @param params
	 * @return List - ProductMG
	 * @throws Exception
	 * @author DH-Xxj
	 */
	@Override
    public List<ProductMG> queryGroupList(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));	//常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        PageUtils.startPageStronger();
        return businessMapper.selectgroup(params);
    }
	
	/**
	 * 保存
	 * @param moduleTable 必要参数：功能唯一标识
	 * @param infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
	 * @param infoItems 必要参数：对应实体类的json格式字符串
	 * @return AjaxResult
	 * @author DH-Xxj
	 */
	@SuppressWarnings("unchecked")
	@Override
    public AjaxResult saveData(Map<String, Object> params) {
		params.put("businessEntity", new ProductMG());
		
		AjaxResult ajaxResult = this.saveDataBase(params);
		if (!"0".equals(ajaxResult.get("code").toString())){
			throw new RuntimeException(ajaxResult.get("msg").toString());
		}

		String resNid = "0";
		Map<String, Object> infoMap = (Map<String, Object>) ajaxResult.get("infoMap");
        List<ProductMG> businessDataList = (List<ProductMG>) ajaxResult.get("businessDataList");

    	List<RecordCheck> guidMapList = businessMapper.findRecords(infoMap.get("nid").toString());
    	Map<String, Object> guidMap = new HashMap<String, Object>();
    	if (!guidMapList.isEmpty() && guidMapList.size() > 0){
    		if (infoMap.get("newNid") != null && "1".equals(infoMap.get("newNid").toString())){ //单号重复验证
    			throw new RuntimeException(MessageUtils.message("module.error.retry"));
    		}
        	for (RecordCheck recordCheck : guidMapList){
        		if (recordCheck != null && recordCheck.getGuid() != null){
            		guidMap.put(recordCheck.getGuid().toString(), "1");
        		}
        	}
    	}
    	
		if (businessDataList == null || businessDataList.size() == 0){
			resNid = "0";
		}else{
			resNid = infoMap.get("nid").toString();
	        for (ProductMG businessData : businessDataList) {
	        	String guid = "";
	        	if (businessData.getGuid() == null){
	        		guid = RandomValueUtils.getGUID();
	        		businessData.setGuid(guid);
	        	}else{
	        		guid = businessData.getGuid().toString();
	        	}
	        	
	        	for (String field : infoMap.keySet()){ //遍历非网格字段，并赋值到实体中
	        		Object fieldValue = infoMap.get(field);
	        		ReflectUtils.setValue(businessData, field, fieldValue);
	        	}
	        	
	        	if (guidMap.get(guid) == null){
	        		businessMapper.insert(businessData);
	        	}else{
	        		businessMapper.update(businessData);
	        		guidMap.remove(guid);
	        	}
	        }
		}
			
    	if (!guidMap.isEmpty()){
    		for (String guid : guidMap.keySet()){
    			businessMapper.delete(guid);
    		}
    	}
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"),resNid);
    }
	
	/**
	 * 删除
	 * @param infoItems 必要参数：对应实体类的json格式字符串
	 * @return AjaxResult
	 * @author DH-Xxj
	 */
	@Override
    public AjaxResult deleteData(Map<String, Object> params) {
        List<ProductMG> businessDataList = JSON.parseArray(params.get("infoItems").toString(), ProductMG.class);
        if (businessDataList == null || businessDataList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.jsontoentyerror"));
        }
        for (ProductMG businessData : businessDataList) {
        	businessMapper.delete(businessData);
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }
	
	/**
	 * 修改删除标志（预留）
	 * @param infoItems 必要参数：对应实体类的json格式字符串（仅需 guid 和 deleted）
	 * @return AjaxResult
	 * @author DH-Xxj
	 */
	@Override
    public AjaxResult updateDeleted(Map<String, Object> params) {
        List<UpdateDeleted> updateDeletedList = JSON.parseArray(params.get("infoItems").toString(), UpdateDeleted.class);
        if (updateDeletedList == null || updateDeletedList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.jsontoentyerror"));
        }
        for (UpdateDeleted updateDeleted : updateDeletedList) {
        	businessMapper.updateDeleted(updateDeleted);
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }
	
	/**
	 * 流转  —— 添加流程任务、修改流程状态及生效标志
	 * @param tableDataId 必要参数：单据编码（nid）
	 * @return AjaxResult
	 * @author DH-Xxj
	 */
	@Override
    public AjaxResult updateFlowGo(Map<String, Object> params) {
		Map<String, Object> infoMap = new HashMap<String, Object>();
		String nid = "0";
		if (params.get("tableDataId") == null || params.get("tableDataId") ==""){
			return AjaxResult.error(MessageUtils.message("module.error.lack","单据编码【tableDataId】"));
		}else{
			nid = params.get("tableDataId").toString();
		}
		params.put("nid", nid);
		List<ProductMG> businessDataList = businessMapper.selectByNid(params);
		if (businessDataList == null || businessDataList.size() == 0){
			return AjaxResult.error(MessageUtils.message("module.error.nodata"));
		}else{
			infoMap.put("cid", businessDataList.get(0).getCid());
			infoMap.put("bUser", businessDataList.get(0).getbUser());
			infoMap.put("bDept", businessDataList.get(0).getbDept());
			infoMap.put("procInstId", businessDataList.get(0).getProcInstId());
			infoMap.put("activeFlow", businessDataList.get(0).getActiveFlow());
			infoMap.put("createTime", businessDataList.get(0).getCreateTime());
			params.put("infoMap", TypeUtils.mapToJson(infoMap).toString());
			params.put("activeFlowOld", businessDataList.get(0).getActiveFlow());
		}
		
		//流程处理公共方法，返回单据（流转、回退等）后的流程状态信息
    	if (params.get("optType") == null || params.get("optType") == ""){
    		params.put("optType", "go");
    	}
		UpdateFlow updateFlow = new UpdateFlow();
    	updateFlow = this.FlowDealBase(params);
		
        for (ProductMG businessData : businessDataList) {
        	updateFlow.setGuid(businessData.getGuid().toString());
        	businessMapper.updateFlow(updateFlow);
        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), nid);
    }
	
	/**
	 * 退回  —— 添加流程任务、修改流程状态及生效标志
	 * @param tableDataId 必要参数：单据编码（nid）
	 * @return AjaxResult
	 * @author DH-Xxj
	 */
	@Override
    public AjaxResult updateFlowBack(Map<String, Object> params) {
		Map<String, Object> infoMap = new HashMap<String, Object>();
		String nid = "0";
		if (params.get("tableDataId") == null || params.get("tableDataId") ==""){
			return AjaxResult.error(MessageUtils.message("module.error.lack","单据编码【tableDataId】"));
		}else{
			nid = params.get("tableDataId").toString();
		}
		params.put("nid", nid);
		List<ProductMG> businessDataList = businessMapper.selectByNid(params);
		if (businessDataList == null || businessDataList.size() == 0){
			return AjaxResult.error(MessageUtils.message("module.error.nodata"));
		}else{
			infoMap.put("cid", businessDataList.get(0).getCid());
			infoMap.put("bUser", businessDataList.get(0).getbUser());
			infoMap.put("bDept", businessDataList.get(0).getbDept());
			infoMap.put("procInstId", businessDataList.get(0).getProcInstId());
			infoMap.put("activeFlow", businessDataList.get(0).getActiveFlow());
			infoMap.put("createTime", businessDataList.get(0).getCreateTime());
			params.put("infoMap", TypeUtils.mapToJson(infoMap).toString());
			params.put("activeFlowOld", businessDataList.get(0).getActiveFlow());
		}
		
		//流程处理公共方法，返回单据（流转、回退等）后的流程状态信息
    	if (params.get("optType") == null || params.get("optType") == ""){
    		params.put("optType", "back");
    	}
		UpdateFlow updateFlow = new UpdateFlow();
    	updateFlow = this.FlowDealBase(params);
		
        for (ProductMG businessData : businessDataList) {
        	updateFlow.setGuid(businessData.getGuid().toString());
        	businessMapper.updateFlow(updateFlow);
        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), nid);
    }

}
